package views;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import util.Constants;

import com.grupp42.te.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * Search menu gui class
 * 
 * @author Simon, Christian
 * 
 */
public class Search extends Activity {

	private EditText searchQuery;
	private Spinner spinner;
	private String[] outString;

	private TableLayout tl;
	private ScrollView sv;
	private TableRow tmpRow;
	private TextView tmpText;
	private Button tmpButton;

	private boolean isAltered;
	private HashMap<String, Integer> searchCode;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		/* The string that will be sent back to appActivity. */
		outString = new String[2];
		isAltered = false;
		sv = new ScrollView(this);
		tl = new TableLayout(this);

		/* Sets the view to the search layout. */
		setContentView(R.layout.search);

		/*
		 * Fetches the different menu-options from the strings.xml and puts them
		 * in the spinner.
		 */
		spinner = (Spinner) findViewById(R.id.ModeSpinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.mode_array, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);

		/* Sets a reference to the query EditText field. */
		searchQuery = (EditText) findViewById(R.id.editText1);

		/* Sets a reference to the submit button. */
		Button submitButton = (Button) findViewById(R.id.submitSearch);

		spinner.setOnItemSelectedListener(SpinnerListener);
		submitButton.setOnClickListener(submitListener);

		/* 
		 * Checks if a list of previously selected hits are passed along on
		 * start and if so draws them out, and adds a viewbutton as well. 
		 */
		Intent intent = this.getIntent();
		Object obj = intent.getSerializableExtra("searchCode");
		if (obj != null) {
			searchCode = (HashMap<String, Integer>) intent
					.getSerializableExtra("searchCode");

			if (!searchCode.isEmpty()) {
				for (Entry<String, Integer> entry : searchCode.entrySet()) {
					tl.addView(createListElement(entry));
				}
				sv.addView(tl);
				RelativeLayout RelLayout = (RelativeLayout) findViewById(R.id.RelLayout);
				LayoutParams p = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		        p.addRule(RelativeLayout.BELOW, submitButton.getId());
				RelLayout.addView(sv,p);
				
				Button viewButton = new Button(this);
				viewButton.setText("View");
				p = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		        p.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		        p.addRule(RelativeLayout.CENTER_HORIZONTAL);
		        RelLayout.addView(viewButton, p);

			}
		} 
	}

	/*
	 * listener for the button, gets the query from the EditText field and sets
	 * it to the outString.
	 */
	private OnClickListener submitListener = new OnClickListener() {

		public void onClick(View v) {
			if (searchQuery.getText().toString().length() > 1) {
				if (searchQuery.getText().toString() == null) {
					outString[0] = "emptyQuery";
				} else {
					outString[0] = searchQuery.getText().toString();
				}

				Intent outIntent = new Intent();

				outIntent.putExtra("Search", outString);
				outIntent.putExtra("searchCode", searchCode);
				setResult(Constants.RESPONSEMAINTOSEARCH, outIntent);
				finish();
				// Toast.makeText(Search.this, "" + outString[0] + outString[1],
				// Toast.LENGTH_SHORT).show();

			} else {
				Toast.makeText(Search.this,
						"Query too short, please use atleast two characters.",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	/* Listener for the spinner. Sets the selected mode to the outString. */
	private OnItemSelectedListener SpinnerListener = new OnItemSelectedListener() {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			outString[1] = parent.getItemAtPosition(pos).toString();
		}

		public void onNothingSelected(AdapterView<?> parent) {
			// Do nothing.
		}

	};
	
	
	/*Captures the back key*/
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	    	Intent outIntent = new Intent();
			if(isAltered){
				outIntent.putExtra("searchCode", searchCode);

				setResult(Constants.RESPONSESEARCHSTARTMAINALTERED, outIntent);
				finish();
			} else {

				setResult(Constants.RESPONSESEARCHSTARTMAIN, outIntent);
			
				finish();
			}
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}

	/**
	 * to be made into a row
	 * @param queryEntry
	 * @return TableRow representing one search hit
	 * 
	 */
	private TableRow createListElement(final Entry<String, Integer> queryEntry) {
		tmpRow = new TableRow(this);
		tmpText = new TextView(this);
		tmpText.setText(queryEntry.getKey());
		tmpRow.addView(tmpText);
		tmpButton = new Button(this);
		tmpButton.setText("Remove");
		final TableRow fixRef = tmpRow;
		tmpButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				searchCode.remove(queryEntry.getKey());
				isAltered = true;

				fixRef.setVisibility(View.GONE);
			}
		});
		tmpRow.addView(tmpButton);
		return tmpRow;

	}

}
